﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Web.UI;

namespace SampleProject
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Title = "Sample Application";

            Assembly web = null;

            try
            {
                //for web application proj
                web = Assembly.Load("App_Code");
            }
            catch
            {
                //for web site proj
                web = Assembly.GetExecutingAssembly();
            }

            AssemblyName webName = web.GetName();

            string myVersion = webName.Version.ToString();


            lblVersion.Text = myVersion;
        }

        protected void btnPost_Click(object sender, EventArgs e)
        {
            string comment = txtComment.Text;

            string connString = ConfigurationManager.ConnectionStrings["SampleApplicationConnectionString"].ConnectionString;
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(connString);
                conn.Open();

                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.Text;
                    //cmd.CommandText = "INSERT INTO [SampleApplication.Comments](Comment, Username) Values (@comment, @username)";
                    cmd.CommandText = "INSERT INTO [SampleApplication.Comments](Comment) Values (@comment)";
                    cmd.Parameters.AddWithValue("@comment", comment);
                    //cmd.Parameters.AddWithValue("@username", Page.User.Identity.Name);
                    int rowsAffected = cmd.ExecuteNonQuery();
                    if (rowsAffected == 1)
                    {
                        //Success notification
                        txtComment.Text = string.Empty;
                        rptComments.DataBind();
                        upComments.Update();
                    }
                    else
                    {
                        //Error notification
                        lblError.Text = "Error in adding comment";
                        upError.Update();
                    }
                }
            }
            catch (Exception ex)
            {
                //log error 
                //display friendly error to user
                lblError.Text = "Error in adding comment:" + ex.Message;
                upError.Update();
            }
            finally
            {
                if (conn != null)
                {
                    //cleanup connection i.e close 
                }
            }

        }
    }
}